<template>
  <div class="login-page">
    <video autoplay loop muted>
      <source src="../../assets/videos/login.mp4" type="video/mp4" />
      Your browser does not support the video tag.
    </video>
    <el-form
      :model="loginFrom"
      status-icon
      :rules="rules"
      ref="loginFrom"
      label-width="100px"
      class="demo-loginFrom"
    >
      <el-form-item><h1>你们这是自寻死路！</h1></el-form-item>
      <el-form-item label="用户:" prop="username">
        <el-input
          type="text"
          v-model="loginFrom.username"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input
          type="password"
          v-model="loginFrom.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码:" prop="captcha">
        <el-input
          class="captcha"
          type="text"
          v-model="loginFrom.captcha"
          autocomplete="off"
        ></el-input>
        <span class="captcha-svg" 
        @click="refreshCaptcha"
        v-html="captchaSvg"></span>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="submitForm('loginFrom')"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//引入封装好的api
import { login, getCaptcha, verifyCaptcha } from "@/api";
import { mapMutations } from "vuex";

export default {
  data() {
    //jsDoc
    /**
     *  @param {object} rule 表单验证对象
     * @param {string} value 输入值
     * @param {function} callback 校验通过不传参,不通过传参
     */
    var validateUsername = (rule, value, callback) => {
      // console.log(rule);
      // console.log(value);

      //登入逻辑的实现:
      //1.收集用户输入的username和password传递给后端
      // 2.登入通过后,将后端返回的token存到本地,跳转到主页
      // 3.每次请求的时候,携带token请求头Authorization
      // 4.展示token检验正确的数据
      // 5.检验不通过,转跳到登录页
      if (!value) {
        callback("必须是4-10位字母、数字、下划线,不能以数字开头");
      } else {
        callback();
      }
    };
    //校验密码
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    //检验验证码
    var validateCaptcha = (rule, value, callback) => {
      if (value === "" || value.length !== 5) {
        callback(new Error("请输入正确的验证码"));
      } else {
        callback();
      }
    };
    return {
      captchaSvg: "", //从服务器上获取的验证码svg解构
      loginFrom: {
        username: "",
        password: "",
        captcha: ""
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.set_captcha();
  },
  methods: {
    //刷新验证码
    refreshCaptcha(){
      getCaptcha().then(res => {
        this.set_captcha()

      });
    },
    //设置验证码
    set_captcha() {
      getCaptcha().then(res => {
        this.captchaSvg = res.data.img;
      });
    },
    ...mapMutations(["SET_USERINFO"]),
    submitForm(formName) {
      // console.log(this.$refs[formName]);
      this.$refs[formName].validate(async valid => {
        if (valid) {
          //表示本地校验通过
          //先验证验证码是否正确,如果正确了再发送登录请求
          let varfiyRes = await verifyCaptcha(this.loginFrom.captcha);
          if (!varfiyRes.data.state) {
            //验证码不正确
            this.$message.error("验证码错误");
            return;
          }
          // console.log(varfiyRes);
          //登录加载
          const loading = this.$loading({
            lock: true,
            text: "登陆中>>>",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)"
          });

          let { username, password } = this.loginFrom;
          login(username, password)
            .then(res => {
              //服务器响应关闭加载
              loading.close();
              if (res.data.state) {
                this.$message.success("登录成功");
                //从后端接受数据设置localStorage
                localStorage.setItem("stu-token", res.data.token);
                localStorage.setItem(
                  "stu-userInfo",
                  JSON.stringify(res.data.userInfo)
                );
                //同时更改vuex中state['userInfo']的值
                this.SET_USERINFO(res.data.userInfo);
                this.$router.push("/Welcome");
              } else {
                this.$message.error("用户名或密码错误");
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          console.log("登录有误!!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
